package com.huxiu.yd;

import com.huxiu.yd.utils.Constants;
import com.huxiu.yd.utils.ImageUtils;
import com.huxiu.yd.utils.LogUtils;
import com.huxiu.yd.utils.Settings;
import com.huxiu.yd.utils.Utils;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.constant.WBConstants;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.utils.Utility;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by yao on 15/9/1:下午9:04.
 */
public class ShareActivity extends BaseActivity
        implements View.OnClickListener, IWeiboHandler.Response,
        WeiboAuthListener, IUiListener {

    @InjectView(R.id.share_qq)
    TextView shareQQ;

    @InjectView(R.id.share_timeline)
    TextView shareTimeline;

    @InjectView(R.id.share_weixin)
    TextView shareWeixin;

    @InjectView(R.id.share_weibo)
    TextView shareWeibo;

    @InjectView(R.id.copy_link)
    TextView copyLink;

    @InjectView(R.id.share_qzone)
    TextView shareQzone;

    @InjectView(R.id.cancel)
    TextView cancel;

    @InjectView(R.id.content)
    protected View content;

    @InjectView(R.id.background)
    protected View background;

    private String title;

    private String link;

    private String type;

    private String imageUrl;

    private String description;

    private Bitmap image;

    private IWeiboShareAPI mWeiboApi;

    protected SsoHandler mSsoHandler;

    protected IWXAPI mWechatApi;

    private Tencent mTencent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share);
        ButterKnife.inject(this);
        LogUtils.d("ShareActivity, onCreate, content is " + content);
        background.setOnClickListener(this);
        cancel.setOnClickListener(this);
        shareQQ.setOnClickListener(this);
        shareTimeline.setOnClickListener(this);
        shareWeixin.setOnClickListener(this);
        shareWeibo.setOnClickListener(this);
        copyLink.setOnClickListener(this);
        shareQzone.setOnClickListener(this);
        title = getIntent().getStringExtra("title");
        link = getIntent().getStringExtra("url");
        type = getIntent().getStringExtra("type");
        image = getIntent().getParcelableExtra("image");
        imageUrl = getIntent().getStringExtra("imageUrl");
        description = getIntent().getStringExtra("description");
        mWechatApi = WXAPIFactory.createWXAPI(this, Constants.WECHAT_KEY);
        mTencent = Tencent.createInstance(Constants.TENCENT_APP_ID, getApplicationContext());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cancel:
                finish();
                break;
            case R.id.background:
                finish();
                break;
            case R.id.share_weibo:
                shareWeibo();
                finish();
                break;
            case R.id.share_weixin:
                shareWeChatFriends();
                finish();
                break;
            case R.id.share_timeline:
                shareWeChatTimeline();
                finish();
                break;
            case R.id.share_qq:
                shareQQ();
                finish();
                break;
            case R.id.share_qzone:
                shareQzone();
                finish();
                break;
            case R.id.copy_link:
                Utils.doCopy(link);
                Utils.showToast(R.string.copied);
                finish();
                break;
        }
    }

    private void shareQQ() {
        Bundle b = new Bundle();
        b.putString(QQShare.SHARE_TO_QQ_TITLE, title);
        if (!TextUtils.isEmpty(description)) {
            String s = description;
            if (s.length() > 40) {
                s = description.substring(0, 40);
            }
            b.putString(QQShare.SHARE_TO_QQ_SUMMARY, s);
        }
        if (!TextUtils.isEmpty(imageUrl)) {
            b.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, imageUrl);
        }
        if (!TextUtils.isEmpty(link)) {
            b.putString(QQShare.SHARE_TO_QQ_TARGET_URL, link);
        }
        b.putString(QQShare.SHARE_TO_QQ_APP_NAME, getString(R.string.app_name));
        b.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        b.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_ITEM_HIDE);
        mTencent.shareToQQ(this, b, this);
    }

    private void shareQzone() {
        Bundle b = new Bundle();
        b.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);
        if (!TextUtils.isEmpty(description)) {
            String s = description;
            if (s.length() > 40) {
                s = description.substring(0, 40);
            }
            b.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, s);
        }
        if (!TextUtils.isEmpty(imageUrl)) {
            ArrayList<String> list = new ArrayList<>();
            list.add(imageUrl);
            b.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, list);
        }
        if (!TextUtils.isEmpty(link)) {
            b.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, link);
        }
        b.putString(QzoneShare.SHARE_TO_QQ_APP_NAME, getString(R.string.app_name));
        b.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);

        mTencent.shareToQzone(this, b, this);
    }

    protected void shareWeChatTimeline() {
        shareWeChat(mWechatApi, link, title, description, ImageUtils.getWeChatShareBitmap(image),
                true);
    }

    protected void shareWeChatFriends() {
        shareWeChat(mWechatApi, link, title, description, ImageUtils.getWeChatShareBitmap(image),
                false);
    }


    private void shareWeChat(IWXAPI wechatApi, String url, String title,
                             String description, Bitmap bitmap, boolean isTimeline) {
        if (!wechatApi.isWXAppInstalled()) {
            Toast.makeText(this, R.string.wechat_not_installed, Toast.LENGTH_SHORT)
                    .show();
            return;
        } else if (!wechatApi.isWXAppSupportAPI()) {
            Toast.makeText(this, R.string.wechat_not_supported, Toast.LENGTH_SHORT)
                    .show();
            return;
        }

        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = title;
        if (description != null) {
            msg.description = description;
        }

        msg.setThumbImage(bitmap);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "webpage" + +System.currentTimeMillis();
        req.message = msg;
        req.scene = isTimeline ? SendMessageToWX.Req.WXSceneTimeline
                : SendMessageToWX.Req.WXSceneSession;
        boolean b = wechatApi.sendReq(req);
    }

    protected void shareWeibo() {
        mWeiboApi = WeiboShareSDK.createWeiboAPI(this, Constants.SINA_APP_KEY);
        mWeiboApi.registerApp();
        if (!mWeiboApi.isWeiboAppInstalled()) {
            Utils.showToast(R.string.weibo_not_installed);
            return;
        }

        WeiboMultiMessage multmess = new WeiboMultiMessage();
        TextObject textObject = new TextObject();
        textObject.text = link;
        multmess.textObject = textObject;
        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
        WebpageObject mediaObject = new WebpageObject();
        mediaObject.identify = Utility.generateGUID();
        mediaObject.title = title;
        mediaObject.description = "";
        mediaObject.setThumbImage(bmp);
        mediaObject.actionUrl = link;
        mediaObject.defaultText = "";
        multmess.mediaObject = mediaObject;

        SendMultiMessageToWeiboRequest multRequest = new SendMultiMessageToWeiboRequest();
        multRequest.multiMessage = multmess;
        multRequest.transaction = String.valueOf(System.currentTimeMillis());
        mWeiboApi.sendRequest(this, multRequest);
    }

    protected void initWeiBo() {
        AuthInfo weiboAuth = new AuthInfo(this, Constants.SINA_APP_KEY,
                Constants.SINA_APP_REDIRECT_URI, Constants.SINA_SCOPE);
        mSsoHandler = new SsoHandler(this, weiboAuth);
        mSsoHandler.authorize(this);
    }


    @Override
    public void onResponse(BaseResponse baseResponse) {
        switch (baseResponse.errCode) {
            case WBConstants.ErrorCode.ERR_OK:
                Toast.makeText(this, R.string.weibo_share_success, Toast.LENGTH_LONG)
                        .show();
                finish();
                break;
            case WBConstants.ErrorCode.ERR_CANCEL:
                Toast.makeText(this, R.string.weibo_share_cancel, Toast.LENGTH_LONG)
                        .show();
                break;
            case WBConstants.ErrorCode.ERR_FAIL:
                Toast.makeText(this,
                        getString(R.string.weibo_share_failed) + ": " + baseResponse.errMsg,
                        Toast.LENGTH_LONG).show();
                break;
        }

    }

    @Override
    public void onComplete(Bundle bundle) {
        Oauth2AccessToken weiboToken = Oauth2AccessToken.parseAccessToken(bundle);
        Settings.saveWeiboAccessToken(weiboToken);
    }

    @Override
    public void onWeiboException(WeiboException e) {

    }

    @Override
    public void onComplete(Object o) {

    }

    @Override
    public void onError(UiError uiError) {
        LogUtils.d("QQ Log In failed: " + uiError.errorDetail + ", " + uiError.errorMessage);
        Toast.makeText(this, TextUtils
                        .isEmpty(uiError.errorDetail) ? getString(R.string.share_failed)
                        : uiError.errorDetail,
                Toast.LENGTH_SHORT
        )
                .show();

    }

    @Override
    public void onCancel() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mSsoHandler != null) {
            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }

    @Override
    public void finish() {
        background.setBackgroundColor(getResources().getColor(android.R.color.transparent));
        super.finish();
        overridePendingTransition(R.anim.push_out_to_bottom, R.anim.push_out_to_bottom);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.push_in_from_bottom);
        LogUtils.d("BasePopupActivity, onStart, content is " + content);
        content.startAnimation(animation);
        AlphaAnimation animation1 = new AlphaAnimation(0.0f, 1.0f);
        animation1.setDuration(200);
        animation1.setFillAfter(true);
        background.startAnimation(animation1);
    }

}
